package com.ihighest.app.infox.activity;

import org.json.JSONException;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.base.AbstractActivity;
import com.ihighest.app.common.core.Application;
import com.ihighest.app.common.kit.AppKit;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.common.kit.ToastKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.myview.ActivityTitle;
import com.ihighest.app.infox.myview.InvitedFriendDialog;
import com.ihighest.app.infox.myview.SettingImgView;
import com.umeng.fb.FeedbackAgent;

/**
 * 我 界面
 * 
 * @author lkx Created at 2015-10-2 下午3:47:30
 * @version 1.0
 */
public class PersonalActivity extends AbstractActivity implements OnClickListener {
	private ActivityTitle title;
	private RelativeLayout loginLayout;
	private RelativeLayout noLoginLayout;
	private TextView uesrName, rankName, inviteCode, goleCount, integral, answer, accept, aggree;
	private ImageView userIcon, rankImage, mQrCode;
	private String imgurl;
	private ReflashBroadcast reflashBroadcast;// 广播接收器
	private SettingImgView personalGoodAssessment, personalMyAnswer, personalMyCollection, personalMyMessage, personalMyPrescription,
			personalInviredFriend, personalPrizeFeedBack, personalPerfectInformation, personFriendCode;
	private ChangeBroadcast changeBroadcast;
	private String qrCode;// 二维码地址
	private String friendCode;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Application.getInstance().addActivity(this);
		setContentView(R.layout.infox_activity_personal);
		initView();
		// reflashBroadcast = new ReflashBroadcast();
		// IntentFilter filter = new IntentFilter();
		// filter.addAction(Const.FINISHLOGIN);
		// registerReceiver(reflashBroadcast, filter);

	}

	/**
	 * 界面刷新的广播接收器
	 * 
	 * @author lkx Created at 2015-11-4 上午10:01:48
	 * @version 1.0
	 */
	public class ReflashBroadcast extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// 得到数据变化的广播
			if (intent.getAction().equals(Const.FINISHLOGIN)) {
				System.out.println("刷新");
				// initView();
				if (TextUtils.isEmpty(SharedPreferencesKit.getString(PersonalActivity.this, Const.SP_KEY_USER_ID))) {
					personalGoodAssessment.setClickable(false);
					// personalMyAnswer.setClickable(false);
					personalMyCollection.setClickable(false);
					personalMyMessage.setClickable(false);
					findViewById(R.id.personalMyChat).setClickable(true);
					// personalMyPrescription.setClickable(false);
					personalInviredFriend.setClickable(false);
					personalPrizeFeedBack.setClickable(false);
					answer.setText("0");
					accept.setText("0");
					aggree.setText("0");
					noLoginLayout.setVisibility(View.VISIBLE);
					loginLayout.setVisibility(View.GONE);
				} else {
					noLoginLayout.setVisibility(View.GONE);
					loginLayout.setVisibility(View.VISIBLE);
					uesrName.setText(SharedPreferencesKit.getString(PersonalActivity.this, Const.SP_KEY_USER_NAME));

				}

			}

		}

	}

	/**
	 * 初始化
	 * 
	 * 
	 * @author lkx Created at 2015-10-13 上午10:19:24
	 */
	private void initView() {
		title = (ActivityTitle) findViewById(R.id.infox_personalTitle);
		title.setTitle("我");
		title.setViewVersible(title.titleMsg, title.titleSetting);
		title.setViewGone(title.rightLayout, title.titleRefresh);

		changeBroadcast = new ChangeBroadcast();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Const.CHANGECOUNT);
		this.registerReceiver(changeBroadcast, filter);
		mQrCode = (ImageView) findViewById(R.id.myQrCord);
		noLoginLayout = (RelativeLayout) findViewById(R.id.NoLoginLayout);
		loginLayout = (RelativeLayout) findViewById(R.id.LoginLayout);
		uesrName = (TextView) findViewById(R.id.userName);
		inviteCode = (TextView) findViewById(R.id.inviteCode);
		goleCount = (TextView) findViewById(R.id.goldCount);
		integral = (TextView) findViewById(R.id.integralCount);
		userIcon = (ImageView) findViewById(R.id.userImg);
		rankName = (TextView) findViewById(R.id.rankName);
		rankImage = (ImageView) findViewById(R.id.rankImg);
		answer = (TextView) findViewById(R.id.answerCount);
		accept = (TextView) findViewById(R.id.acceptCount);
		aggree = (TextView) findViewById(R.id.agreeCount);
		personalGoodAssessment = (SettingImgView) findViewById(R.id.personalGoodAssessment);
		personalMyAnswer = (SettingImgView) findViewById(R.id.personalMyAnswer);
		personalMyCollection = (SettingImgView) findViewById(R.id.personalMyCollection);
		personalMyMessage = (SettingImgView) findViewById(R.id.personalMyMessage);
		personalPerfectInformation = (SettingImgView) findViewById(R.id.personalPerfectInformation);
		// personalMyPrescription = (SettingImgView)
		// findViewById(R.id.personalMyPrescription);
		personalInviredFriend = (SettingImgView) findViewById(R.id.personalInviredFriend);
		personalPrizeFeedBack = (SettingImgView) findViewById(R.id.personalPrizeFeedBack);
		personFriendCode = (SettingImgView) findViewById(R.id.personalFeiendCode);
		findViewById(R.id.login).setOnClickListener(this);
		personFriendCode.setOnClickListener(this);
		if (TextUtils.isEmpty(SharedPreferencesKit.getString(PersonalActivity.this, Const.SP_KEY_USER_ID))) {
			// personalGoodAssessment.setClickable(false);
			// personalMyAnswer.setClickable(false);
			// personalMyCollection.setClickable(false);
			// personalMyMessage.setClickable(false);
			// personalMyPrescription.setClickable(false);
			// personalInviredFriend.setClickable(false);
			// personalPrizeFeedBack.setClickable(false);
			noLoginLayout.setVisibility(View.VISIBLE);
			loginLayout.setVisibility(View.GONE);
		} else {
			noLoginLayout.setVisibility(View.GONE);
			loginLayout.setVisibility(View.VISIBLE);
			uesrName.setText(SharedPreferencesKit.getString(PersonalActivity.this, Const.SP_KEY_USER_NAME));
		}
		setOnclick();
		title.titleSetting.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(PersonalActivity.this, SettingActivity.class);

				startActivity(intent);

			}
		});
		mQrCode.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				QrCodeDialog dialog = new QrCodeDialog(PersonalActivity.this, R.style.CustomDialog);
				dialog.show();
			}
		});

	}

	private void setOnclick() {
		findViewById(R.id.copyCode).setOnClickListener(new OnClickListener() {

			@SuppressLint("NewApi")
			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View arg0) {
				if (TextUtils.isEmpty(SharedPreferencesKit.getString(PersonalActivity.this, Const.SP_KEY_USER_ID))) {
					Intent intent = new Intent(PersonalActivity.this, LoginActivity.class);
					ToastKit.showShort(PersonalActivity.this, Const.UN_LOGIN_ALERT);
					startActivity(intent);
				} else {
					ClipboardManager clip = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
					// clip.getText(); // 粘贴
					if (Build.VERSION.SDK_INT >= 11) {
						ClipData clipData = ClipData.newPlainText("邀请码", inviteCode.getText());
						clip.setPrimaryClip(clipData);
					} else {
						clip.setText(inviteCode.getText());
					}
					ToastKit.showShort(getApplicationContext(), "已复制");
				}
			}
		});
		personalGoodAssessment.setOnClickListener(this);
		personalMyAnswer.setOnClickListener(this);
		personalMyCollection.setOnClickListener(this);
		personalPerfectInformation.setOnClickListener(this);
		// findViewById(R.id.personalMyEncyclopedia).setOnClickListener(this);
		personalMyMessage.setOnClickListener(this);
		findViewById(R.id.personalMyChat).setOnClickListener(this);
		// personalMyPrescription.setOnClickListener(this);
		personalInviredFriend.setOnClickListener(this);
		personalPrizeFeedBack.setOnClickListener(this);

		userIcon.setOnClickListener(this);
		initData();
	}

	/**
	 * 初始化数据
	 * 
	 * 
	 * @author lkx Created at 2015-10-17 下午3:43:02
	 */
	private void initData() {
		// 加载会员信息
		if (!TextUtils.isEmpty(SharedPreferencesKit.getString(PersonalActivity.this, Const.SP_KEY_USER_ID))) {

			Api.get("me/details", null, new ApiCallback(PersonalActivity.this, true) {

				@Override
				public void handleSuccess(ApiResult result) {
					try {
						uesrName.setText(result.getData().getString("name"));
						integral.setText(result.getData().getInt("integral") + "");
						goleCount.setText(result.getData().getInt("coin") + "");
						inviteCode.setText(result.getData().getString("code"));
						SharedPreferencesKit.putString(PersonalActivity.this, Const.USER_InvitedCode, result.getData().getString("code"));
						accept.setText(result.getData().getInt("accept") + "");
						aggree.setText(result.getData().getInt("agree") + "");
						answer.setText(result.getData().getInt("answer") + "");
						imgurl = result.getData().getString("header");
						System.out.println("头像地址" + imgurl);
						qrCode = result.getData().getString("myQrCode");
						friendCode = result.getData().getString("oinvitationCoded");
						SharedPreferencesKit.putString(PersonalActivity.this, Const.SP_KEY_USER_HEADER, imgurl);

						// DisplayImageOptions defaultOptions = new
						// DisplayImageOptions.Builder()

						// .showImageForEmptyUri(R.drawable.infox_person_no_icon).showImageOnFail(R.drawable.infox_person_no_icon)
						// .showImageOnLoading(R.drawable.infox_person_no_icon).cacheInMemory(true).cacheOnDisc(true).build();
						// ImageLoader.getInstance().displayImage(imgurl,
						// userIcon, defaultOptions);
						AppKit.SetUserImg(imgurl, userIcon);
						// ImageLoader.getInstance().displayImage(qrCode,
						// mQrCode, defaultOptions);
						if ("Specialist".equalsIgnoreCase(result.getData().getString("type"))) {
							rankImage.setVisibility(View.VISIBLE);
							rankName.setText(result.getData().getString("rank"));
							// ImageLoader.getInstance().displayImage(result.getData().getString("rankImage"),
							// rankImage, defaultOptions);
							AppKit.SetNormalImg(result.getData().getString("rankImage"), rankImage);
							// ImageLoader.getInstance().displayImage(result.getData().getString("rankImage"),
							// rankImage);
						} else {
							rankName.setText("");
							rankImage.setVisibility(View.INVISIBLE);
						}
						if (!TextUtils.isEmpty(friendCode)) {
							personFriendCode.setClickable(false);
							personFriendCode.setItemName("您已经填写邀请码：" + friendCode);
						} else {
							personFriendCode.setItemName("请填写好友的邀请码");
							personFriendCode.setClickable(true);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void handleFailure(Exception e, String msg) {
				}
			}, PersonalActivity.this);

			Api.data("member/info/m_" + SharedPreferencesKit.getString(PersonalActivity.this, Const.SP_KEY_USER_ID) + ".json",
					new ApiCallback(PersonalActivity.this, true) {

						@Override
						public void handleSuccess(ApiResult result) {

							System.out.println(result.getData().toString());
							try {
								String profession = result.getData().getString("profession");
								SharedPreferencesKit.putString(PersonalActivity.this, Const.PROFESSION, profession);

							} catch (JSONException e) {
								e.printStackTrace();
							}

						}

						@Override
						public void handleFailure(Exception e, String msg) {

						}
					}, PersonalActivity.this);
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		Log.e("", "进入Me");
		if (Const.UNREADMESSAGE != 0) {
			title.messagenumber.setText(Const.UNREADMESSAGE + "");
			title.messagenumber.setVisibility(View.VISIBLE);
		} else {
			title.messagenumber.setVisibility(View.GONE);
		}

		if (TextUtils.isEmpty(SharedPreferencesKit.getString(PersonalActivity.this, Const.SP_KEY_USER_ID))) {
			friendCode = "";
			// personalGoodAssessment.setClickable(false);
			// personalMyAnswer.setClickable(false);
			// personalMyCollection.setClickable(false);
			// personalMyMessage.setClickable(false);
			// personalMyPrescription.setClickable(false);
			// personalInviredFriend.setClickable(false);
			// personalPrizeFeedBack.setClickable(false);
			noLoginLayout.setVisibility(View.VISIBLE);
			loginLayout.setVisibility(View.GONE);
			personFriendCode.setItemName("请填写好友的邀请码");
			personFriendCode.setClickable(true);
		} else {
			personalGoodAssessment.setClickable(true);
			// personalMyAnswer.setClickable(true);
			personalMyCollection.setClickable(true);
			personalMyMessage.setClickable(true);
			findViewById(R.id.personalMyChat).setClickable(true);
			// personalMyPrescription.setClickable(true);
			personalInviredFriend.setClickable(true);
			personalPrizeFeedBack.setClickable(true);
			setOnclick();
			noLoginLayout.setVisibility(View.GONE);
			loginLayout.setVisibility(View.VISIBLE);
			uesrName.setText(SharedPreferencesKit.getString(PersonalActivity.this, Const.SP_KEY_USER_NAME));

		}

	}

	@SuppressLint("NewApi")
	@Override
	public void onClick(View v) {
		Intent intent = null;
		switch (v.getId()) {
		case R.id.personalPerfectInformation:
			if (TextUtils.isEmpty(SharedPreferencesKit.getString(this, Const.SP_KEY_USER_ID))) {
				intent = new Intent(this, LoginActivity.class);
				ToastKit.showShort(this, Const.UN_LOGIN_ALERT);
				startActivity(intent);
			} else {
				intent = new Intent(PersonalActivity.this, PerfectInformationActivity.class);
				intent.putExtra("icon", imgurl);
				intent.putExtra("name", uesrName.getText().toString());
				startActivity(intent);
			}
			break;
		case R.id.personalFeiendCode:
			if (TextUtils.isEmpty(SharedPreferencesKit.getString(this, Const.SP_KEY_USER_ID))) {
				intent = new Intent(this, LoginActivity.class);
				ToastKit.showShort(this, Const.UN_LOGIN_ALERT);
				startActivity(intent);
			} else {
				intent = new Intent(PersonalActivity.this, SetFriendInvitedCode.class);
				startActivity(intent);
			}
			break;
		case R.id.personalGoodAssessment:
			try {
				intent = new Intent(Intent.ACTION_VIEW);
				intent.setData(Uri.parse("market://details?id=" + getPackageName()));
				// intent.setData(Uri.parse("market://search?q=pub:金草帽"));
				startActivity(intent);
			} catch (Exception ex) {
				ToastKit.showShort(this, "没有找到市场");
			}
			break;
		case R.id.userImg:
			if (TextUtils.isEmpty(SharedPreferencesKit.getString(this, Const.SP_KEY_USER_ID))) {
				intent = new Intent(this, LoginActivity.class);
				ToastKit.showShort(this, Const.UN_LOGIN_ALERT);
				startActivity(intent);
			} else {
				intent = new Intent(PersonalActivity.this, SetNameAndIconActivity.class);
				intent.putExtra("personActivity", "person");
				intent.putExtra("icon", imgurl);
				intent.putExtra("name", uesrName.getText().toString());
				startActivity(intent);
			}
			break;
		case R.id.personalInviredFriend:
			if (TextUtils.isEmpty(SharedPreferencesKit.getString(this, Const.SP_KEY_USER_ID))) {
				intent = new Intent(this, LoginActivity.class);
				ToastKit.showShort(this, Const.UN_LOGIN_ALERT);
				startActivity(intent);
			} else {
				Api.get("share", ApiParam.create().addParam("type", "AppLoad"), new ApiCallback(PersonalActivity.this) {

					@Override
					public void handleFailure(Exception e, String msg) {
					}

					@Override
					public void handleSuccess(ApiResult result) {

						try {
							InvitedFriendDialog dialog = new InvitedFriendDialog(PersonalActivity.this, R.style.CustomDialog);

							dialog.setShareId(result.getData().getString("ShareId"));
							dialog.show();
						} catch (JSONException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}

					}
				}, PersonalActivity.this);

			}
			break;
		case R.id.personalMyAnswer:
			if (TextUtils.isEmpty(SharedPreferencesKit.getString(this, Const.SP_KEY_USER_ID))) {
				intent = new Intent(this, LoginActivity.class);
				ToastKit.showShort(this, Const.UN_LOGIN_ALERT);
				startActivity(intent);
			} else {
				intent = new Intent(PersonalActivity.this, MyQuestionAndAnswerActivity.class);
				intent.putExtra("title", "我的问答");
				startActivity(intent);
			}
			break;
		case R.id.personalMyCollection:
			if (TextUtils.isEmpty(SharedPreferencesKit.getString(this, Const.SP_KEY_USER_ID))) {
				intent = new Intent(this, LoginActivity.class);
				ToastKit.showShort(this, Const.UN_LOGIN_ALERT);
				startActivity(intent);
			} else {
				intent = new Intent(PersonalActivity.this, MyCollectionActivity.class);
				startActivity(intent);
			}
			break;
		// case R.id.personalMyColumn:
		// intent = new Intent(PersonalActivity.this, PleaseWaitActivity.class);
		// break;
		// case R.id.personalMyEncyclopedia:
		// intent = new Intent(PersonalActivity.this, PleaseWaitActivity.class);
		// break;
		case R.id.personalMyMessage:
			if (TextUtils.isEmpty(SharedPreferencesKit.getString(this, Const.SP_KEY_USER_ID))) {
				intent = new Intent(this, LoginActivity.class);
				ToastKit.showShort(this, Const.UN_LOGIN_ALERT);
				startActivity(intent);
			} else {
				intent = new Intent(PersonalActivity.this, MyMassageActivity.class);
				intent.putExtra("title", "我的消息");
				startActivity(intent);
			}
			break;
		case R.id.personalMyChat:
			if (TextUtils.isEmpty(SharedPreferencesKit.getString(this, Const.SP_KEY_USER_ID))) {
				intent = new Intent(this, LoginActivity.class);
				ToastKit.showShort(this, Const.UN_LOGIN_ALERT);
				startActivity(intent);
			} else {
				intent = new Intent(PersonalActivity.this, ConversationListActivity.class);
				intent.putExtra("title", "我的会话");
				startActivity(intent);
			}
			break;
		// case R.id.personalMyPrescription:
		// if (TextUtils.isEmpty(SharedPreferencesKit.getString(this,
		// Const.SP_KEY_USER_ID))) {
		// intent = new Intent(this, LoginActivity.class);
		// ToastKit.showShort(this, Const.UN_LOGIN_ALERT);
		// startActivity(intent);
		// } else {
		//
		// }
		// break;
		case R.id.personalPrizeFeedBack:
			FeedbackAgent agent = new FeedbackAgent(this);
			agent.startFeedbackActivity();
			break;
		case R.id.login:
			intent = new Intent(PersonalActivity.this, LoginActivity.class);
			startActivity(intent);
			break;

		}

	}

	@Override
	public void onBackPressed() {

		super.onBackPressed();
	}

	public class ChangeBroadcast extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// 得到数据变化的广播
			if (intent.getAction().equals(Const.CHANGECOUNT)) {
				if (Const.UNREADMESSAGE != 0) {
					title.messagenumber.setText(Const.UNREADMESSAGE + "");
					title.messagenumber.setVisibility(View.VISIBLE);
				} else {
					title.messagenumber.setVisibility(View.GONE);
				}

			}

		}

	}

	class QrCodeDialog extends Dialog {
		private ImageView img;

		public QrCodeDialog(Context context, int theme) {
			super(context, theme);
			this.requestWindowFeature(Window.FEATURE_NO_TITLE);
			setCustomDialog();
		}

		public QrCodeDialog(Context context) {
			super(context);
			this.requestWindowFeature(Window.FEATURE_NO_TITLE);
			setCustomDialog();
		}

		private void setCustomDialog() {

			View mView = LayoutInflater.from(PersonalActivity.this).inflate(R.layout.infox_activity_person_bigqrcode, null);
			initView(mView);

			super.setContentView(mView);
		}

		private void initView(View view) {
			img = (ImageView) view.findViewById(R.id.mBigQrCode);
			AppKit.SetNormalImg(qrCode, img);
			// ImageLoader.getInstance().displayImage(qrCode, img);
			img.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View arg0) {
					dismiss();

				}
			});

		}

	}

}
